<script setup lang='ts'>
import { ref, reactive } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import _ from 'lodash'
import { Search, Minus, Plus } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { useEnumStore } from "@/store/enumeration";
import useInstance from "@/hooks/useInstance";
import { useComListData } from "@/store/list"
import { equityPackageAddPost } from "@/api/equity"
defineOptions({
    name: "addPackage",
});


const { listCollect } = useComListData()
const ruleFormRef = ref<FormInstance>();


const {
    grantType,
    packageUseType,
    expiryPeriodType
} = useEnumStore();
const emit = defineEmits(["refresh"]);
const { global } = useInstance();

const dialogBasic = ref({
    title: "新建权益包",
    visible: false,
    width: 1200,
    height: 300,
    showFooter: false,
    marginTop: "10vh",
})


// 如何设计 就是单独操作 最后在弄在一起 
const packageForm = reactive({
    packageCode: null,// 权益包编码
    packageName: null,// 权益包名称
    packageUsageMode: 1,// 权益配置项使用方式
    packageConfigRespDTOS: [] as any,//  最后的数据
    reduceMoney: [] as any,//立减金
    ParkingVoucher: [] as any,//停车券 
    virtualMember: [] as any,//虚拟会员
})

const rules = reactive<FormRules>({
    packageName: [
        {
            required: true,
            trigger: "blur",
            message: "请输入权益包名称",
        },
    ],
})

//显示弹框
const show = (type: string, row?: any) => {
    dialogBasic.value.visible = true

    if (type == 'add') {
        packageForm.reduceMoney.push({
            packageConfigType: 1,
            equityCode: null,//优惠编码
            equityName: null,//优惠名称
            grantNum: null,// 发放数量
            minusMoney: null,// 立减金额
            receiveUrl: null,// 用户领取链接
            grantType: null,// 发放方式
            grantIntervalTime: null,// 发放时常
            timeUnit: 2,// 时长单位

        })
        packageForm.ParkingVoucher.push({
            packageConfigType: 2,
            equityCode: null,//优惠编码
            equityName: null,//优惠名称
            grantNum: null,// 发放数量
            minusMoney: null,// 立减金额
            receiveUrl: null,// 用户领取链接
            grantType: null,// 发放方式
            grantIntervalTime: null,// 发放时常
            timeUnit: 2,// 时长单位

        })
        packageForm.virtualMember.push({
            packageConfigType: 3,
            equityCode: null,//优惠编码
            equityName: null,//优惠名称
            grantNum: null,// 发放数量
            minusMoney: null,// 立减金额
            receiveUrl: null,// 用户领取链接
            grantType: null,// 发放方式
            grantIntervalTime: null,// 发放时常
            timeUnit: 2,// 时长单位

        })
    } else {
        Object.assign(packageForm, row)
        const arr1 = row.packageConfigRespDTOS && row.packageConfigRespDTOS.filter((item: any) => item.packageConfigType == 1)
        const arr2 = row.packageConfigRespDTOS && row.packageConfigRespDTOS.filter((item: any) => item.packageConfigType == 2)
        const arr3 = row.packageConfigRespDTOS && row.packageConfigRespDTOS.filter((item: any) => item.packageConfigType == 3)
        if (!arr1) {
            packageForm.reduceMoney.push({
                packageConfigType: 1,
                equityCode: null,//优惠编码
                equityName: null,//优惠名称
                grantNum: null,// 发放数量
                minusMoney: null,// 立减金额
                receiveUrl: null,// 用户领取链接
                grantType: null,// 发放方式
                grantIntervalTime: null,// 发放时常
                timeUnit: 2,// 时长单位

            })
        } else {
            packageForm.ParkingVoucher = arr1

        }
        if (!arr2) {
            packageForm.ParkingVoucher.push({
                packageConfigType: 2,
                equityCode: null,//优惠编码
                equityName: null,//优惠名称
                grantNum: null,// 发放数量
                minusMoney: null,// 立减金额
                receiveUrl: null,// 用户领取链接
                grantType: null,// 发放方式
                grantIntervalTime: null,// 发放时常
                timeUnit: 2,// 时长单位

            })
        } else {
            packageForm.reduceMoney = arr2

        }
        if (!arr3) {
            packageForm.virtualMember.push({
                packageConfigType: 3,
                equityCode: null,//优惠编码
                equityName: null,//优惠名称
                grantNum: null,// 发放数量
                minusMoney: null,// 立减金额
                receiveUrl: null,// 用户领取链接
                grantType: null,// 发放方式
                grantIntervalTime: null,// 发放时常
                timeUnit: 2,// 时长单位

            })
        } else {
            packageForm.virtualMember = arr3
        }
        packageForm.packageConfigRespDTOS = []

    }
}
const addMoney = (num: number, type: number) => {
    if (type == 1) {
        const arr = {
            packageConfigType: 1,
            equityCode: null,//优惠编码
            equityName: null,//优惠名称
            grantNum: null,// 发放数量
            minusMoney: null,// 立减金额
            receiveUrl: null,// 用户领取链接
            grantType: null,// 发放方式
            grantIntervalTime: null,// 发放时常
            timeUnit: 2,// 时长单位
        }
        packageForm.reduceMoney.splice(num + 1, 0, arr)
    }
    if (type == 3) {
        const arr = {
            packageConfigType: 3,
            equityCode: null,//优惠编码
            equityName: null,//优惠名称
            grantNum: null,// 发放数量
            minusMoney: null,// 立减金额
            receiveUrl: null,// 用户领取链接
            grantType: null,// 发放方式
            grantIntervalTime: null,// 发放时常
            timeUnit: 2,// 时长单位
        }
        packageForm.virtualMember.splice(num + 1, 0, arr)
    }

}

const minMoney = (item: number, type: number) => {
    if (type == 1) {
        const index = packageForm.reduceMoney.indexOf(item)
        if (index !== -1) {
            packageForm.reduceMoney.splice(index, 1)
        }
    }
    if (type == 3) {
        const index = packageForm.virtualMember.indexOf(item)
        if (index !== -1) {
            packageForm.virtualMember.splice(index, 1)
        }
    }


}
const radioChange = (item: any) => {
    console.log(item);
    if (item.grantType == '1') {
        item.receiveUrl = null
    }
}
const money = (val: any, type: number) => {
    if (val.equityCode) {
        listCollect.equityList && listCollect.equityList.forEach((item: any) => {
            if (item.key == val.equityCode) {
                val.equityName = item.objName
            }
            if (type == 1) {
                val.money = item.money
            }
        })
    } else {
        ruleFormRef.value?.clearValidate()
    }

}

const onClose = () => {
    dialogBasic.value.visible = false
    // @ts-ignore
    Object.keys(packageForm).forEach((item) => packageForm[item] = null)
    packageForm.packageUsageMode = 1
    packageForm.reduceMoney = []
    packageForm.virtualMember = []
    packageForm.packageConfigRespDTOS = []
    packageForm.ParkingVoucher = []


}
const onConfirm = async () => {
    const arr: any = {}
    packageForm.packageConfigRespDTOS = []
    Object.assign(arr, packageForm)

    await ruleFormRef.value?.validate(async isOk => {
        if (isOk) {
            arr.reduceMoney && arr.reduceMoney.forEach((item: any) => {
                if (item.equityCode) {
                    item.minusMoney = item.money && item.grantNum && item.money * item.grantNum
                    delete item.money
                    arr.packageConfigRespDTOS.push(item)
                }
            })
            arr.ParkingVoucher && arr.ParkingVoucher.forEach((item: any) => {
                if (item.equityCode) {
                    arr.packageConfigRespDTOS.push(item)
                }
            })
            arr.virtualMember && arr.virtualMember.forEach((item: any) => {
                if (item.equityCode) {
                    arr.packageConfigRespDTOS.push(item)
                }
            })
            delete arr.reduceMoney
            delete arr.ParkingVoucher
            delete arr.virtualMember

            const res = await equityPackageAddPost(arr);
            if (res.code == 20000) {
                ElMessage({
                    type: "success",
                    message: packageForm.id ? "权益包编辑成功" : "权益包新增成功",
                });
                emit("refresh");
                onClose();
            }
        } else {
            ElMessage({
                type: "error",
                message: packageForm.id
                    ? "权益包编辑失败 请重试！"
                    : "权益包新增失败 请重试！",
            });
        }
    })
}
defineExpose({
    show
})
</script>

<template>
    <SysDialog :title="dialogBasic.title" :width="dialogBasic.width" :height="dialogBasic.height"
        :show-footer="dialogBasic.showFooter" :visible="dialogBasic.visible" :margin-top="dialogBasic.marginTop"
        @on-close="onClose" @on-confirm="onConfirm">
        <template v-slot:content>
            <div class="channel-form" v-loading="false">
                <el-form ref="ruleFormRef" :model="packageForm" :rules="rules" label-width="130px" class="demo-ruleForm"
                    status-icon>
                    <el-form-item label="权益包" prop="packageName">
                        <normal-input v-model:model-value="packageForm.packageName" maxlength="120" disabled
                            show-word-limit></normal-input>
                    </el-form-item>
                    <el-form-item label="立减金" v-if="packageForm.reduceMoney && packageForm.reduceMoney.length > 1">
                        <el-radio-group v-model="packageForm.packageUsageMode" >
                            <el-radio v-for="(item, index) in packageUseType" :label="item.value" :key="index"
                            disabled :value="item.id"> </el-radio>
                        </el-radio-group>
                    </el-form-item>

                    <template v-for="(item, index1) in packageForm.reduceMoney" :key="index1">
                        <el-row>
                            <el-col :span="5">
                                <el-form-item label="立减金" label-width="80px">
                                    <el-select v-model="item.equityCode" @change="money(item, 1)" filterable disabled
                                        style="width: 200px; margin-right:10px" placeholder="立减金" clearable>
                                        <el-option v-for="item in listCollect.equityList" :key="item.id"
                                            :label="item.value" :value="item.key" />
                                    </el-select>

                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="领取数量" label-width="80px"
                                    :prop="'reduceMoney.' + index1 + '.grantNum'" :rules="item.equityCode ? {
                                        required: true,
                                        message: '请输入领取数量',
                                        trigger: 'blur',
                                    } : {}">
                                    <el-input-number v-model.number="item.grantNum" clearable
                                    disabled :min="1" :max="999" placeholder="数量 0-999"
                                        :controls="false" />
                                </el-form-item>
                            </el-col>

                            <el-col :span="6">
                                <el-form-item label="发放方式" label-width="80px"
                                    :prop="'reduceMoney.' + index1 + '.grantType'" :rules="item.equityCode ? {
                                        required: true,
                                        message: '请选择发放方式',
                                        trigger: 'blur',
                                    } : {}">
                                    <el-radio-group v-model="item.grantType" disabled
                                        @change="radioChange(item)">
                                        <el-radio v-for="(item, index) in grantType" :label="item.value" :key="index"
                                            :value="item.id"></el-radio>
                                    </el-radio-group>
                                </el-form-item>
                            </el-col>
                            <el-col :span="5">
                                <el-form-item label="领取链接" v-if="item.grantType == 2" label-width="70px"
                                    :prop="'reduceMoney.' + index1 + '.receiveUrl'" :rules="item.equityCode ? {
                                        required: true,
                                        message: '请输入领取链接',
                                        trigger: 'blur',
                                    } : {}">
                                    <el-input v-model.trim="item.receiveUrl" :maxlength="256"
                                        style="width: 200px; margin-right:10px" clearable></el-input>
                                </el-form-item>
                            </el-col>
                          
                            <el-col :span="5">
                                <el-form-item label="时长间隔" label-width="80px"
                                    :prop="'reduceMoney.' + index1 + '.grantIntervalTime'" :rules="item.equityCode ? {
                                        required: true,
                                        message: '请输入时长间隔',
                                        trigger: 'blur',
                                    } : {}">
                                    <el-input v-model.number="item.grantIntervalTime" style="width: 150px"
                                        placeholder="时长间隔" disabled>
                                        <template #append>
                                            <BlackSelect style="width: 60px;" v-model:select-value="item.timeUnit"
                                                disabled :options="expiryPeriodType"></BlackSelect>
                                        </template>
                                    </el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="4">
                                <el-form-item label="月立减金额" label-width="90px">
                                    {{ item.minusMoney }} 元
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </template>
                    <el-divider />
                    <template v-for="(item, index1) in packageForm.ParkingVoucher" :key="index1">
                        <el-row>
                            <el-col :span="5">
                                <el-form-item label="停车券" label-width="80px">
                                    <el-select v-model="item.equityCode" @change="money(item, 2)" filterable disabled
                                        style="width: 200px; margin-right:10px" placeholder="停车券" clearable>
                                        <el-option v-for="item in listCollect.equityList" :key="item.id"
                                            :label="item.value" :value="item.key" />
                                    </el-select>

                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="领取数量" label-width="80px"
                                    :prop="'ParkingVoucher.' + index1 + '.grantNum'" :rules="item.equityCode ? {
                                        required: true,
                                        message: '请输入领取数量',
                                        trigger: 'blur',
                                    } : {}">
                                    <el-input-number v-model.number="item.grantNum" clearable 
                                    disabled :min="1" :max="999" placeholder="数量 0-999"
                                        :controls="false" />
                                </el-form-item>
                            </el-col>

                            <el-col :span="6">
                                <el-form-item label="发放方式" label-width="80px"
                                    :prop="'ParkingVoucher.' + index1 + '.grantType'" :rules="item.equityCode ? {
                                        required: true,
                                        message: '请选择发放方式',
                                        trigger: 'blur',
                                    } : {}">
                                    <el-radio-group v-model="item.grantType" disabled
                                        @change="radioChange(item)">
                                        <el-radio v-for="(item, index) in grantType" :label="item.value" :key="index"
                                            :value="item.id"></el-radio>
                                    </el-radio-group>
                                </el-form-item>
                            </el-col>
                            <el-col :span="5">
                                <el-form-item label="领取链接" v-if="item.grantType == 2" label-width="80px"
                                    :prop="'ParkingVoucher.' + index1 + '.receiveUrl'" :rules="item.equityCode ? {
                                        required: true,
                                        message: '请选择发放方式',
                                        trigger: 'blur',
                                    } : {}">
                                    <el-input v-model.trim="item.receiveUrl" :maxlength="256" disabled
                                        style="width: 200px; margin-right:10px" clearable></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="5">
                                <el-form-item label="时长间隔" label-width="80px"
                                    :prop="'ParkingVoucher.' + index1 + '.grantIntervalTime'" :rules="item.equityCode ? {
                                        required: true,
                                        message: '请输入时长间隔',
                                        trigger: 'blur',
                                    } : {}">
                                    <el-input v-model.number="item.grantIntervalTime" style="width: 150px"
                                        placeholder="时长间隔" disabled>
                                        <template #append>
                                            <BlackSelect style="width: 60px;" v-model:select-value="item.timeUnit"
                                                disabled :options="expiryPeriodType"></BlackSelect>
                                        </template>
                                    </el-input>
                                </el-form-item>
                            </el-col>

                        </el-row>
                    </template>
                    <el-divider />
                    <template v-for="(item, index1) in packageForm.virtualMember" :key="index1">
                        <el-row>
                            <el-col :span="5">
                                <el-form-item label="虚拟会员" label-width="80px">
                                    <el-select v-model="item.equityCode" @change="money(item, 3)" filterable disabled
                                        style="width: 200px; margin-right:10px" placeholder="虚拟会员" clearable>
                                        <el-option v-for="item in listCollect.equityList" :key="item.id"
                                            :label="item.value" :value="item.key" />
                                    </el-select>

                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="领取数量" label-width="80px"
                                    :prop="'virtualMember.' + index1 + '.grantNum'" :rules="item.equityCode ? {
                                        required: true,
                                        message: '请输入时长间隔',
                                        trigger: 'blur',
                                    } : {}">
                                    <el-input-number v-model.number="item.grantNum" clearable
                                    disabled :min="1" :max="999" placeholder="数量 0-999"
                                        :controls="false" />
                                </el-form-item>
                            </el-col>

                            <el-col :span="6">
                                <el-form-item label="发放方式" label-width="80px"
                                    :prop="'virtualMember.' + index1 + '.grantType'" :rules="item.equityCode ? {
                                        required: true,
                                        message: '请选择发放方式',
                                        trigger: 'blur',
                                    } : {}">
                                    <el-radio-group v-model="item.grantType" disabled
                                        @change="radioChange(item)">
                                        <el-radio v-for="(item, index) in grantType" :label="item.value" :key="index"
                                            :value="item.id"></el-radio>
                                    </el-radio-group>
                                </el-form-item>
                            </el-col>
                            <el-col :span="5">
                                <el-form-item label="领取链接" v-if="item.grantType == 2" label-width="80px"
                                    :prop="'virtualMember.' + index1 + '.receiveUrl'" :rules="item.equityCode ? {
                                        required: true,
                                        message: '请输入领取链接',
                                        trigger: 'blur',
                                    } : {}">
                                    <el-input v-model.trim="item.receiveUrl" :maxlength="256" disabled
                                        style="width: 200px; margin-right:10px" clearable></el-input>
                                </el-form-item>
                            </el-col>
                      
                            <el-col :span="5">
                                <el-form-item label="时长间隔" label-width="80px"
                                    :prop="'virtualMember.' + index1 + '.grantIntervalTime'" :rules="item.equityCode ? {
                                        required: true,
                                        message: '请输入时长间隔',
                                        trigger: 'blur',
                                    } : {}">
                                    <el-input v-model.number="item.grantIntervalTime" style="width: 150px"
                                        placeholder="时长间隔" disabled>
                                        <template #append>
                                            <BlackSelect style="width: 60px;" v-model:select-value="item.timeUnit"
                                                disabled :options="expiryPeriodType"></BlackSelect>
                                        </template>
                                    </el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </template>


                </el-form>
            </div>
        </template>
    </SysDialog>
</template>

<style lang='scss' scoped>
.channel-form {
    height: 600px;
    overflow: auto;
}

:deep(.el-radio__inner) {
    border-radius: 2px !important;
}

:deep(.el-radio__input.is-checked .el-radio__inner::after) {
    content: '';
    width: 8px;
    height: 3px;
    border: 1px solid black;
    border-top: transparent;
    border-right: transparent;
    text-align: center;
    display: block;
    position: absolute;
    top: 3px;
    left: 2px;
    transform: rotate(-45deg);
    border-radius: 0px;
    background: none;
}
</style>
